#!/usr/bin/env python

#    Tichy
#
#    copyright 2008 Guillaume Chereau (charlie137@gmail.com)
#
#    This file is part of Tichy.
#
#    Tichy is free software: you can redistribute it and/or modify it
#    under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Tichy is distributed in the hope that it will be useful, but
#    WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#    General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Tichy.  If not, see <http://www.gnu.org/licenses/>.

import sys
import os

from distutils.core import setup
from distutils.extension import Extension
from glob import glob
import commands

# We check if we don't have the c files in tichy/guic. If so then we try
# to use cython to generate them.
for file_ in glob("./tichy/guic/*.pyx"):
    if not os.path.exists(file_.replace(".pyx", ".c")):
        use_cython = True
        break
else:
    use_cython = False

if use_cython:
    from Cython.Distutils import build_ext
    cmdclass = {'build_ext': build_ext}
else:
    cmdclass = {}


def plugins_files():
    """generate the plugins data files list

    It works by adding all the files ending with a set of specified
    extension to the data. So we have to be careful when adding files
    with new extension we have to add it here as well.
    """
    ret = []
    for root, dirs, files in os.walk('./bin/plugins/'):
        if root.endswith('.svn'):
            dirs[:] = []
            continue
        # XXX: Where is the best place to put the plugins files ???
        dest = 'share/tichy/plugins/' + root[len("./bin/plugins/"):]
        src = []
        for file in files:
            if file.endswith((".py", ".png", ".dic", ".txt", ".yaml")):
                path = '%s/%s' % (root, file)
                src.append(path)
        ret.append((dest, src))
    return ret


def resources_files():
    ret = []
    for root, dirs, files in os.walk('./res/'):
        if root.endswith('.svn'):
            dirs[:] = []
            continue
        dest = 'share/tichy/res/' + root[len('./res/'):]
        src = []
        for file in files:
            if file.endswith((".png", ".txt")):
                path = '%s/%s' % (root, file)
                src.append(path)
        ret.append((dest, src))
    return ret


def make_extension(name):
    """Create an extension for a given guic file
    """
    flags_map = {'-I': 'include_dirs', '-L': 'library_dirs',
                 '-l': 'libraries'}

    for cmdline in ['pkg-config --libs --cflags sdl',
                    'sdl-config --libs --cflags']:
        status, output = commands.getstatusoutput(cmdline)
        if status == 0:
            break
    else:
        raise Exception("could not find pkg-config module: sdl")

    kargs = {}
    for token in output.split():
        if token[:2] in flags_map:
            kargs.setdefault(flags_map[token[:2]], []).append(token[2:])
        else:
            kargs.setdefault("extra_compile_args", []).append(token)

    file_ext = 'pyx' if use_cython else 'c'
    return Extension('%s' % name,
                     sources=['tichy/guic/%s.%s' % (name, file_ext)],
                     **kargs)


setup(name='tichy',
      version='1.1.0',
      description='Python Applet Manager for Openmoko',
      author="Guillaume 'charlie' Chereau",
      author_email='charlie137@gmail.com',
      # url='',
      packages = ['tichy', 'tichy.guic', 'tichy.guip',
                  'tichy.phone', 'tichy.prefs'],
      scripts= ['bin/tichy'],
      data_files = [('share/applications', ['data/tichy.desktop']),
                    ('share/pixmaps', ['data/tichy.png'])]
          + plugins_files() + resources_files(),
      ext_package='tichy.guic',
      ext_modules=[make_extension(x) for x in [
            'geo', 'cobject', 'widget', 'frame', 'painter', 'sdl_painter',
            'surf_widget', 'image']],
      cmdclass=cmdclass)
